import 'dart:async';
import 'dart:ui';

import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_constraintlayout/flutter_constraintlayout.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:wch/utils/color_utils.dart';
import 'package:wch/utils/digital_utils.dart';
import 'package:wch/utils/time_utils.dart';
import 'package:wch/utils/toast_utils.dart';
import 'package:wch/widget/padding_widget.dart';
import 'package:wch/widget/text_widget.dart';
import 'package:webview_flutter/webview_flutter.dart';

import '../constant/config_constant.dart';
import '../constant/resource_constant.dart';
import '../model/flag_model.dart';
import '../model/patient_label.dart';
import '../utils/loading_utils.dart';
import '../utils/log_utils.dart';
import '../utils/overlay_utils.dart';
import '../utils/text_utils.dart';
import 'common_widget.dart';

class SimpleTextAlert extends StatefulWidget {
  const SimpleTextAlert(
      {Key? key, required this.text, required this.entry, required this.callback,})
      : super(key: key);

  final String text;
  final OverlayEntry entry;
  final Function callback;

  @override
  State<SimpleTextAlert> createState() => _SimpleTextAlertState();
}

class _SimpleTextAlertState extends State<SimpleTextAlert> {
  TextEditingController _controller = TextEditingController();
  FocusNode _focusNode = FocusNode();

  @override
  void initState() {
    _controller.text = widget.text;
    _focusNode.requestFocus();
  }

  @override
  Widget build(BuildContext context) {
    return KeyboardDismissOnTap(
      child: GestureDetector(
        onTap: (){
          widget.entry.remove();
          if (_controller.text.isNotEmpty) {
            widget.callback(int.parse(_controller.text));
          }
          _focusNode.unfocus();
        },
        child: Container(
          padding: EdgeInsets.fromLTRB(120.w, 50.h, 120.w, 230.h),
          color: alphaColor,
          child: Container(
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.all(Radius.circular(7.5)),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                VerPadding(5),
                Text('请输入页码', style: TextStyle(fontSize: 15, color: Colors.black, fontWeight: FontWeight.w500),),
                VerPadding(10),
                Container(
                  width: 100,
                  child: CupertinoTextField(
                    placeholderStyle: TextStyle(
                      color: hintColor,
                      fontSize: 15,
                    ),
                    maxLength: 4,
                    controller: _controller,
                    focusNode: _focusNode,
                    textAlign: TextAlign.center,
                    style: TextStyle(color: F1TextColor, fontSize: 15),
                    keyboardType: TextInputType.number,
                  ),
                ),
              ],

            ),
          ),
        ),
      ),
    );
  }
}

class AlertInputWidget extends StatefulWidget {
  AlertInputWidget({
    super.key,
    this.callback,
    required this.btns,
    this.title,
    required this.entry,
    this.msg,
    this.hint,
  });

  final Function? callback;

  final List<String> btns;

  final String? title;

  final String? msg;

  final String? hint;

  final OverlayEntry entry;

  @override
  State<AlertInputWidget> createState() => _AlertInputWidgetState();
}

class _AlertInputWidgetState extends State<AlertInputWidget> {
  String? inputText;

  late TextEditingController _controller;

  FocusNode node = FocusNode();

  @override
  void initState() {
    _controller = TextEditingController();
    _controller.addListener(() {
      setState(() {
        inputText = _controller.text;
      });
    });

    node.requestFocus();

    Timer.periodic(const Duration(seconds: 1), (timer) {
      timer.cancel();
      OverlayUtils.insertOverlay(context: context, entry: widget.entry);
    });
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: (){
        widget.entry!.remove();
        OverlayUtils.removeOverlay();
      },
      child: Container(
        color: alphaColor,
        child: Center(
          child: Container(
            width: ScreenUtil().screenWidth - 90.w,
            decoration: BoxDecoration(
              color: popupViewColor,
              borderRadius: BorderRadius.circular(20.h),
            ),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                VerPadding(29.h),
                Text(
                  widget.title!,
                  style: TextStyle(
                    fontSize: 16,
                    color: Color(0xFF262626),
                    fontWeight: FontWeight.w600,
                  ),
                ),
                VerPadding(16.h),
                widget.msg != null ? Column(
                  children: [
                    F13TitleText(widget.msg!, color: F1TextColor),
                    VerPadding(10.h),
                  ],
                ) : Container(),
                Container(
                  padding: EdgeInsets.symmetric(horizontal: 30.w),
                  child: CupertinoTextField(
                    focusNode: node,
                    maxLines: 1,
                    obscureText: true,
                    style: TextStyle(fontSize: 14.w, color: F1TextColor),
                    controller: _controller,
                    placeholder: widget.hint,
                    maxLength: 16,
                    placeholderStyle: TextStyle(
                      fontSize: 15,
                      color: Color(0xFFADADAD),
                    ),
                    decoration: BoxDecoration(
                        color: Colors.transparent,
                        borderRadius: BorderRadius.circular(2.5.h),
                        border: Border.all(color: themeColor, width: 0.5.h)),
                  ),
                ),
                VerPadding(20.h),
                LineWidget(width: ScreenUtil().screenWidth - 90.w, height: 0.5.h),
                Container(
                  height: 60.h,
                  child: Row(
                    children: _getBtns(ScreenUtil().screenWidth - 90.w),
                    mainAxisSize: MainAxisSize.max,
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  List<Widget> _getBtns(double totalWidth) {
    List<Widget> list = [];
    double width =
        (totalWidth - (widget.btns.length * 0.5.w)) / (widget.btns.length);
    list.add(GestureDetector(
        onTap: () {
          widget.entry.remove();
          OverlayUtils.removeOverlay();
          widget.callback!(0, inputText ?? '');
        },
        child: Container(
            width: width,
            color: Colors.transparent,
            alignment: Alignment.center,
            height: 60.h,
            child: F16TitleText(widget.btns.first, color: Color(0xFF262626)))));

    for (int i = 1; i < widget.btns.length; i++) {
      list.add(LineWidget(width: 0.5.w, height: 60.h));
      list.add(GestureDetector(
          onTap: () {
            if (inputText == null || inputText!.isEmpty) {
              ///TODO:目前和业务相关，不通用
              Loading.getIns().msg(msg: '请输入密码');
            } else if(inputText!.length < 8) {
              ToastUtils.showToast(msg: '请至少输入8位WiFi密码');
            }
            else {
              widget.callback!(i, inputText ?? '');
              widget.entry.remove();
              OverlayUtils.removeOverlay();
            }
          },
          child: Container(
              width: width,
              alignment: Alignment.center,
              color: Colors.transparent,
              child: F16TitleText(widget.btns[i], color: themeColor))));
    }

    return list;
  }
}

class AlertInputWidget2 extends StatefulWidget {
  AlertInputWidget2({
    super.key,
    this.callback,
    required this.btns,
    this.title,
    required this.entry,
    this.msg,
    this.hint,
  });

  final Function? callback;

  final List<String> btns;

  final String? title;

  final String? msg;

  final String? hint;

  final OverlayEntry entry;

  @override
  State<AlertInputWidget2> createState() => _AlertInputWidgetState2();
}

class _AlertInputWidgetState2 extends State<AlertInputWidget2> {
  String? inputText;

  late TextEditingController _controller;

  FocusNode node = FocusNode();

  @override
  void initState() {
    _controller = TextEditingController();
    _controller.addListener(() {
      setState(() {
        inputText = _controller.text;
      });
    });

    node.requestFocus();

    Timer.periodic(const Duration(seconds: 1), (timer) {
      timer.cancel();
      OverlayUtils.insertOverlay(context: context, entry: widget.entry);
    });
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: (){
        widget.entry!.remove();
        OverlayUtils.removeOverlay();
      },
      child: Container(
        color: alphaColor,
        child: Center(
          child: Container(
            width: ScreenUtil().screenWidth - 90.w,
            decoration: BoxDecoration(
              color: popupViewColor,
              borderRadius: BorderRadius.circular(20.h),
            ),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    GestureDetector(onTap: (){
                      widget.entry.remove();
                    }, child: Container(margin: EdgeInsets.fromLTRB(12.w, 12.w, 15.w, 2.w), child: Image.asset(aboutCloseIcon, width: 12.w, height: 12.w,))),
                  ],
                ),
                Text(
                  widget.title!,
                  style: TextStyle(
                    fontSize: 16,
                    color: Color(0xFF262626),
                    fontWeight: FontWeight.w500,
                  ),
                ),
                VerPadding(16.h),
                widget.msg != null ? Column(
                  children: [
                    F13TitleText(widget.msg!, color: F1TextColor),
                    VerPadding(10.h),
                  ],
                ) : Container(),
                Container(
                  margin: EdgeInsets.symmetric(horizontal: 30.w),
                  height: 40.h,
                  decoration: BoxDecoration(
                      color: const Color(0xFFF3F5FA),
                      borderRadius: BorderRadius.circular(10.h)),
                  child: CupertinoTextField(
                    focusNode: node,
                    maxLines: 1,
                    style: TextStyle(fontSize: 14.w, color: F1TextColor),
                    controller: _controller,
                    placeholder: widget.hint,
                    keyboardType: TextInputType.url,
                    placeholderStyle: TextStyle(
                      fontSize: 15,
                      color: Color(0xFFADADAD),
                    ),
                    decoration: BoxDecoration(
                      color: Colors.transparent
                    ),

                  ),
                ),
                VerPadding(20.h),
                LineWidget(width: ScreenUtil().screenWidth - 90.w, height: 0.5.h),
                Container(
                  height: 60.h,
                  child: Row(
                    children: _getBtns(ScreenUtil().screenWidth - 90.w),
                    mainAxisSize: MainAxisSize.max,
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  List<Widget> _getBtns(double totalWidth) {
    List<Widget> list = [];
    double width =
        (totalWidth - (widget.btns.length * 0.5.w)) / (widget.btns.length);
    list.add(GestureDetector(
        onTap: () {
          if (!DigitalUtils.isValidUrl(inputText!) && !DigitalUtils.isValidIPAddress(inputText!)) {
            ToastUtils.showToast(msg: '请输入正确的服务器地址');
            return;
          }
          widget.entry.remove();
          OverlayUtils.removeOverlay();
          if (list.length == 1) {
            widget.callback!(0, inputText ?? '');
          }
        },
        child: Container(
            width: width,
            color: Colors.transparent,
            alignment: Alignment.center,
            height: 60.h,
            child: F16TitleText(widget.btns.first, color: themeColor))));

    for (int i = 1; i < widget.btns.length; i++) {
      list.add(LineWidget(width: 0.5.w, height: 60.h));
      list.add(GestureDetector(
          onTap: () {
            if (inputText == null || inputText!.isEmpty) {
              ///TODO:目前和业务相关，不通用
              Loading.getIns().msg(msg: '请输入密码');
            } else {
              widget.callback!(i, inputText ?? '');
              widget.entry.remove();
              OverlayUtils.removeOverlay();
            }
          },
          child: Container(
              width: width,
              alignment: Alignment.center,
              color: Colors.transparent,
              child: F16TitleText(widget.btns[i], color: themeColor))));
    }

    return list;
  }
}

class CommonAlert extends StatefulWidget {
  CommonAlert(
      {super.key,
      required this.title,
      required this.msg,
      this.leftBtnText = '取消',
      this.rightBtnText = '确定',
      this.isSingleBtn = false,
      required this.callback,
      required this.entry});

  final String title;
  final String msg;
  String? leftBtnText;
  String? rightBtnText;
  bool isSingleBtn;
  final Function callback;
  final OverlayEntry entry;

  @override
  State<CommonAlert> createState() => _CommonAlertState();
}

class _CommonAlertState extends State<CommonAlert> {
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: (){
        widget.entry!.remove();
        OverlayUtils.removeOverlay();
      },
      child: Container(
        color: alphaColor,
        child: ConstraintLayout(
          children: [
            Container(
              height: 195.h,
              margin: EdgeInsets.symmetric(horizontal: 45.w),
              decoration: BoxDecoration(
                color: popupViewColor,
                borderRadius: BorderRadius.circular(20.h),
              ),
            ).applyConstraint(
                centerTo: parent,
                left: parent.left.margin(45.w),
                right: parent.right.margin(45.w),
                width: matchConstraint,
                height: 195.h),
            Text(widget.title, style: TextStyle(
              fontSize: 17, color: F1TextColor, fontWeight: FontWeight.w600
            ),).applyConstraint(
                top: rId(0).top.margin(29.h),
                left: parent.left,
                right: parent.right),
            LineWidget(width: ScreenUtil().screenWidth - 90.w, height: 0.5.h)
                .applyConstraint(
              left: parent.left.margin(45.w),
              right: parent.right.margin(45.w),
              width: matchConstraint,
              bottom: rId(0).bottom.margin(60.h),
            ),
            F13TitleText(widget.msg, color: F1TextColor, isAlignCenter: true,).applyConstraint(
                left: parent.left.margin(65.w), right: parent.right.margin(65.w),
                width: matchConstraint, top: rId(1).bottom.margin(16.h),
                bottom: rId(2).top,
              height: matchConstraint
            ),
            Visibility(visible: !widget.isSingleBtn, child: LineWidget(width: 0.5.w, height: 60.h)).applyConstraint(
              top: rId(2).bottom,
              bottom: rId(0).bottom,
              height: matchConstraint,
              centerHorizontalTo: parent,
            ),
            GestureDetector(
                    onTap: () {
                      widget.entry.remove();
                      OverlayUtils.removeOverlay();
                      widget.callback(0);
                    },
                    child: F16TitleText(widget.leftBtnText!, color: widget.isSingleBtn ? themeColor : F2TextColor))
                .applyConstraint(
              top: rId(2).top,
              bottom: rId(4).bottom,
              left: rId(2).left,
              right: widget.isSingleBtn ? rId(2).right : rId(4).right,
              clickPadding: EdgeInsets.all(5.w),
            ),
            Visibility(
              visible: widget.isSingleBtn == false,
              child: GestureDetector(
                      onTap: () {
                        widget.entry.remove();
                        OverlayUtils.removeOverlay();
                        widget.callback(1);
                      },
                      child: F16TitleText(widget.rightBtnText!, color: themeColor)),
            ).applyConstraint(
              top: rId(2).top,
              bottom: rId(4).bottom,
              right: rId(2).right,
              left: rId(4).left,
              clickPadding: EdgeInsets.all(15.w)),
          ],
        ),
      ),
    );
  }

  @override
  void initState() {
    Timer.periodic(const Duration(seconds: 1), (timer) {
      timer.cancel();
      OverlayUtils.insertOverlay(context: context, entry: widget.entry);
    });
  }
}

///横屏弹窗
class VerticalCommonAlert extends StatefulWidget {
  VerticalCommonAlert(
      {super.key,
      required this.title,
      required this.msg,
      this.leftBtnText = '取消',
      this.rightBtnText = '确定',
      required this.callback,
      required this.entry});

  final String title;
  final String msg;
  String? leftBtnText;
  String? rightBtnText;
  final Function callback;
  final OverlayEntry entry;

  @override
  State<VerticalCommonAlert> createState() => _VerticalCommonAlertState();
}

class _VerticalCommonAlertState extends State<VerticalCommonAlert> {
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: (){
        widget.entry!.remove();
        OverlayUtils.removeOverlay();
      },
      child: Container(
        color: alphaColor,
        child: ConstraintLayout(
          children: [
            Container(
              height: 195.h,
              margin: EdgeInsets.symmetric(horizontal: 80.w),
              decoration: BoxDecoration(
                color: popupViewColor,
                borderRadius: BorderRadius.circular(20.h),
              ),
            ).applyConstraint(
                centerTo: parent,
                left: parent.left.margin(45.w),
                right: parent.right.margin(45.w),
                width: matchConstraint,
                height: 195.h),
            Text(widget.title, style: TextStyle(color: F1TextColor, fontSize: 17, fontWeight: FontWeight.w600),).applyConstraint(
                top: rId(0).top.margin(29.h),
                left: parent.left,
                right: parent.right),
            F13TitleText(widget.msg, color: F1TextColor).applyConstraint(
                centerHorizontalTo: parent, top: rId(1).bottom.margin(16.h)),
            LineWidget(width: ScreenUtil().screenWidth - 90.w, height: 0.5.h)
                .applyConstraint(
              left: parent.left.margin(80.w),
              right: parent.right.margin(80.w),
              width: matchConstraint,
              bottom: rId(0).bottom.margin(60.h),
            ),
            LineWidget(width: 0.5.w, height: 60.h).applyConstraint(
              top: rId(3).bottom,
              bottom: rId(0).bottom,
              height: matchConstraint,
              centerHorizontalTo: parent,
            ),
            GestureDetector(
                    onTap: () {
                      widget.entry.remove();
                      OverlayUtils.removeOverlay();
                      widget.callback(0);
                    },
                    child: F16TitleText(widget.leftBtnText!, color: F2TextColor))
                .applyConstraint(
              top: rId(3).top,
              bottom: rId(4).bottom,
              left: rId(3).left,
              right: rId(4).right,
              clickPadding: EdgeInsets.all(5.w),
            ),
            GestureDetector(
                    onTap: () {
                      widget.entry.remove();
                      OverlayUtils.removeOverlay();
                      widget.callback(1);
                    },
                    child: F16TitleText(widget.rightBtnText!, color: themeColor))
                .applyConstraint(
              top: rId(3).top,
              bottom: rId(4).bottom,
              right: rId(3).right,
              left: rId(4).left,
              clickPadding: EdgeInsets.all(15.w),
            )
          ],
        ),
      ),
    );
  }

  @override
  void initState() {
    Timer.periodic(const Duration(seconds: 1), (timer) {
      timer.cancel();
      OverlayUtils.insertOverlay(context: context, entry: widget.entry);
    });
  }
}

class AboutAlert extends StatefulWidget {
  AboutAlert({Key? key, required this.entry}) : super(key: key);

  final OverlayEntry entry;

  @override
  State<AboutAlert> createState() => _AboutAlertState();
}

class _AboutAlertState extends State<AboutAlert> {
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: (){
        widget.entry!.remove();
        OverlayUtils.removeOverlay();
      },
      child: Container(
        color: alphaColor,
        child: ConstraintLayout(
          children: [
            Container(
              height: 195.h,
              width: ScreenUtil().screenWidth - 90.w,
              margin: EdgeInsets.symmetric(horizontal: 45.w),
              decoration: BoxDecoration(
                color: popupViewColor,
                borderRadius: BorderRadius.circular(20.h),
              ),
            ).applyConstraint(
                centerTo: parent,
                left: parent.left.margin(45.w),
                right: parent.right.margin(45.w),
                width: matchConstraint,
                height: 195.h),
            GestureDetector(
                onTap: () {
                  widget.entry.remove();
                },
                child: Container(
                    alignment: Alignment.center,
                    width: 43.w,
                    height: 43.w,
                    child: Image.asset(
                      aboutCloseIcon,
                      width: 13.w,
                      height: 13.w,
                    ))).applyConstraint(
                size: 43.w, right: parent.right.margin(45.w), top: rId(0).top),
            Image.asset(
              aboutAppIcon,
              width: 45.w,
              height: 45.w,
            ).applyConstraint(
              size: 45.w,
              top: rId(1).bottom.margin(17.h),
              centerHorizontalTo: rId(0),
            ),
            F14TitleText('脑电睡眠监测系统', color: F1TextColor).applyConstraint(
              centerHorizontalTo: rId(0),
              top: rId(2).bottom.margin(12.h),
            ),
            F11TitleText('版本 V$appVersion', color: Color(0xFF686868)).applyConstraint(
                centerHorizontalTo: rId(0), top: rId(3).bottom.margin(20.h))
          ],
        ),
      ),
    );
  }

  @override
  void initState() {
    Timer.periodic(const Duration(seconds: 1), (timer) {
      timer.cancel();
      OverlayUtils.insertOverlay(context: context, entry: widget.entry);
    });
  }
}

class ProtocolAlert extends StatefulWidget {
  const ProtocolAlert(
      {super.key,
      required this.entry,
      required this.title,
      required this.htmlStr});

  final OverlayEntry entry;
  final String title;
  final String htmlStr;

  @override
  State<ProtocolAlert> createState() => _ProtocolAlertState();
}

class _ProtocolAlertState extends State<ProtocolAlert> {
  WebViewController? controller;
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: (){
        widget.entry!.remove();
        OverlayUtils.removeOverlay();
      },
      child: Container(
        color: alphaColor,
        child: ConstraintLayout(
          children: [
            Container(
              height: ScreenUtil().screenHeight - 270.h,
              width: ScreenUtil().screenWidth - 90.w,
              margin: EdgeInsets.symmetric(horizontal: 45.w),
              decoration: BoxDecoration(
                color: popupViewColor,
                borderRadius: BorderRadius.circular(20.h),
              ),
            ).applyConstraint(
                centerTo: parent,
                left: parent.left.margin(45.w),
                right: parent.right.margin(45.w),
                width: matchConstraint,
                height: ScreenUtil().screenHeight - 270.h),
            GestureDetector(
                onTap: () {
                  widget.entry.remove();
                },
                child: Container(
                    alignment: Alignment.center,
                    width: 43.w,
                    height: 43.w,
                    child: Image.asset(
                      aboutCloseIcon,
                      width: 13.w,
                      height: 13.w,
                    ))).applyConstraint(
                size: 43.w, right: parent.right.margin(45.w), top: rId(0).top),
            F14TitleText(widget.title, color: F1TextColor).applyConstraint(
              centerHorizontalTo: rId(0),
              top: rId(1).bottom.margin(12.h),
            ),
            Container(
              decoration: BoxDecoration(
                color: popupViewColor,
                borderRadius: BorderRadius.circular(20.h),
              ),
              child: WebViewWidget(controller: controller!,),
            ).applyConstraint(
                left: rId(0).left.margin(60.w),
                right: rId(0).right.margin(60.w),
                width: matchConstraint,
                top: rId(2).bottom.margin(20.h),
                bottom: rId(0).bottom.margin(20.h),
                height: matchConstraint,
                zIndex: 0)
          ],
        ),
      ),
    );
  }

  @override
  void initState() {
    Timer.periodic(const Duration(seconds: 1), (timer) {
      timer.cancel();
      OverlayUtils.insertOverlay(context: context, entry: widget.entry);
    });

    controller = WebViewController();
    controller!.setJavaScriptMode(JavaScriptMode.unrestricted);
    controller!.loadHtmlString(widget.title == '《用户协议条款》' ? agreementStr : privacyStr);
  }
}

///编辑标签弹窗
class EditFlagAlert extends StatefulWidget {
  EditFlagAlert(
      {super.key,
      required this.title,
      this.leftBtnText = '取消',
      this.rightBtnText = '确定',
      required this.entry,
      required this.flagModels,
      required this.actionCallback});

  final String title;
  final List<PatientAllLabelData> flagModels;
  String? leftBtnText;
  String? rightBtnText;
  final Function actionCallback;
  final OverlayEntry entry;

  @override
  State<EditFlagAlert> createState() => _EditFlagAlertState();
}

class _EditFlagAlertState extends State<EditFlagAlert> {
  List<Widget> flagWidgets = [];

  double flagHeight = 0;

  Size _getTextSize(String text, double maxWidth, double fontSize) {
    TextStyle style = TextStyle(
      fontSize: fontSize,
    );
    Size size = TextUtils.boundingTextSize(text, style, maxWidth: maxWidth);
    return Size(size.width, size.height+4);
  }

  ///callback 返回整体的高度
  List<Widget> getEditableFlagsWidget(List<PatientAllLabelData> flags,
      double maxWidth, double maxHeight, double fontSize, Function callback) {
    List<Widget> widgets = [Container()];

    double totalHeight = 10;
    double posX = 0;
    for (int i = 0; i < flags.length; i++) {
      Size size = _getTextSize(flags[i].name!, maxWidth, fontSize);
      if (totalHeight == 10) {
        totalHeight = size.height + 15;
      }
      posX += size.width + 20;
      if (posX > maxWidth) {
        posX = size.width + 20;
        totalHeight += size.height + 15;
      }

      if (totalHeight > maxHeight) {
        break;
      }

      widgets.add(Positioned(
        left: posX - size.width - 20,
        top: totalHeight - size.height - 20,
        width: size.width + 30,
        height: size.height + 15,
        child: Stack(
          children: [
            GestureDetector(
              onTap: () {
                setState(() {
                  bool canChecked = true;
                  if (flags[i].isChecked == false && (flags[i].name == '测' || flags[i].name == '除')) {
                    for (int j = 0; j < flags.length; j ++) {
                      PatientAllLabelData data = flags[j];
                      if ((data.name == '测' || data.name == '除') && data.name != flags[i].name && data.isChecked) {
                        canChecked = false;
                      }
                    }
                  }
                  if (canChecked) {
                    flags[i].isChecked = !flags[i].isChecked;
                  }
                });
              },
              child: Container(
                alignment: Alignment.center,
                width: size.width + 20,
                margin: EdgeInsets.only(top: 10),
                decoration: BoxDecoration(
                    color: ColorUtils.getColorFromHex(flags[i].colour!)
                        .withOpacity(0.2),
                    border: Border.all(color: ColorUtils.getColorFromHex(flags[i].colour!).withOpacity(0.3)),
                    borderRadius: BorderRadius.all(Radius.circular(7.5.w))),
                child: MyText(flags[i].name!,
                    color: ColorUtils.getColorFromHex(flags[i].colour!),
                    fontSize: fontSize),
              ),
            ),
            Positioned(
              child: Offstage(
                  offstage: !flags[i].isChecked,
                  child: Image.asset(
                    flagCheckedIcon,
                    width: 13.w,
                    height: 13.w,
                  )),
              right: 5,
              top: 5,
            )
          ],
        ),
      ));

      posX += 10;
    }
    callback(totalHeight);
    return widgets;
  }

  @override
  Widget build(BuildContext context) {

    flagWidgets = getEditableFlagsWidget(
        widget.flagModels, ScreenUtil().screenWidth - 150.w, 400, 18, (height) {
      flagHeight = height;
    });

    return Container(
      color: alphaColor,
      child: ConstraintLayout(
        children: [
          Container(
            height: 130.h + flagHeight,
            margin: EdgeInsets.symmetric(horizontal: 45.w),
            decoration: BoxDecoration(
              color: popupViewColor,
              borderRadius: BorderRadius.circular(20.h),
            ),
          ).applyConstraint(
              centerTo: parent,
              left: parent.left.margin(45.w),
              right: parent.right.margin(45.w),
              width: matchConstraint,
              height: 130.h + flagHeight),
          Text(widget.title, style: TextStyle(fontSize: 17, color: F1TextColor, fontWeight: FontWeight.w600),).applyConstraint(
              top: rId(0).top.margin(29.h),
              left: parent.left,
              right: parent.right),
          LineWidget(width: ScreenUtil().screenWidth - 90.w, height: 0.5.h)
              .applyConstraint(
            left: parent.left.margin(45.w),
            right: parent.right.margin(45.w),
            width: matchConstraint,
            bottom: rId(0).bottom.margin(60.h),
          ),
          LineWidget(width: 0.5.w, height: 60.h).applyConstraint(
            top: rId(2).bottom,
            bottom: rId(0).bottom,
            height: matchConstraint,
            centerHorizontalTo: parent,
          ),
          GestureDetector(
                  onTap: () {
                    widget.entry.remove();
                    OverlayUtils.removeOverlay();
                    List<PatientAllLabelData> list = [];
                    widget.actionCallback(list);
                  },
                  child: F16TitleText(widget.leftBtnText!, color: F2TextColor))
              .applyConstraint(
            top: rId(2).top,
            bottom: rId(3).bottom,
            left: rId(2).left,
            right: rId(3).right,
            clickPadding: EdgeInsets.all(5.w),
          ),
          GestureDetector(
                  onTap: () {
                    widget.entry.remove();
                    OverlayUtils.removeOverlay();
                    widget.actionCallback(widget.flagModels);
                  },
                  child: F16TitleText(widget.rightBtnText!, color: themeColor))
              .applyConstraint(
            top: rId(2).top,
            bottom: rId(3).bottom,
            right: rId(2).right,
            left: rId(3).left,
            clickPadding: EdgeInsets.all(15.w),
          ),
          Container(
                  height: flagHeight,
                  width: ScreenUtil().screenWidth - 150.w,
                  child: Stack(children: flagWidgets))
              .applyConstraint(
            left: rId(0).left.margin(15.w),
            right: rId(0).right.margin(15.w),
            top: rId(1).bottom.margin(12.h),
            width: ScreenUtil().screenWidth - 150.w,
            height: flagHeight,
          ),
        ],
      ),
    );
  }

  @override
  void initState() {
    Timer.periodic(const Duration(seconds: 1), (timer) {
      timer.cancel();
      OverlayUtils.insertOverlay(context: context, entry: widget.entry);
    });
  }
}

///选择用户模板弹窗
class UserTemplateAlert extends StatefulWidget {
  UserTemplateAlert(
      {super.key,
      required this.title,
      this.leftBtnText = '取消',
      this.rightBtnText = '确定',
      required this.callback,
      required this.entry,
      required this.flagModels,
      required this.selectedId});

  final String title;
  final List<FlagModel> flagModels;
  String? leftBtnText;
  String? rightBtnText;

  ///返回操作
  final Function callback;
  final OverlayEntry entry;

  int selectedId;

  @override
  State<UserTemplateAlert> createState() => _UserTemplateAlertState();
}

class _UserTemplateAlertState extends State<UserTemplateAlert> {
  List<Widget> flagWidgets = [];

  double flagHeight = 0;

  Size _getTextSize(String text, double maxWidth, double fontSize) {
    TextStyle style = TextStyle(
      fontSize: fontSize,
    );
    return TextUtils.boundingTextSize(text, style, maxWidth: maxWidth);
  }

  ///callback 返回整体的高度
  List<Widget> getEditableFlagsWidget(List<FlagModel> flags, double maxWidth,
      double maxHeight, double fontSize, Function callback) {
    List<Widget> widgets = [Container()];

    double totalHeight = 0;
    double posX = 0;
    for (int i = 0; i < flags.length; i++) {
      Size size = _getTextSize(flags[i].flagName, maxWidth, fontSize);
      if (totalHeight == 0) {
        totalHeight = size.height + 30;
      }
      posX += size.width + 20;
      if (posX > maxWidth) {
        posX = size.width + 20;
        totalHeight += size.height + 20;
      }

      if (totalHeight > maxHeight) {
        break;
      }

      widgets.add(Positioned(
        left: posX - size.width - 20,
        top: totalHeight - size.height - 20,
        width: size.width + 30,
        height: size.height + 20,
        child: Stack(
          children: [
            GestureDetector(
              onTap: () {
                setState(() {
                  for (int k = 0; k < flags.length; k++) {
                    flags[k].isChecked = false;
                  }
                  flags[i].isChecked = true;
                  widget.selectedId = i;
                });
              },
              child: Container(
                alignment: Alignment.center,
                width: size.width + 20,
                margin: EdgeInsets.only(top: 10),
                decoration: BoxDecoration(
                    color: const Color(0xFFF3F5FA),
                    border: flags[i].isChecked
                        ? Border.all(color: themeColor, width: 1)
                        : Border.all(color: Colors.transparent, width: 0),
                    borderRadius: BorderRadius.all(Radius.circular(7.5.w))),
                child: MyText(flags[i].flagName,
                    color: flags[i].isChecked ? themeColor : F2TextColor,
                    fontSize: fontSize),
              ),
            ),
            Positioned(
              child: Offstage(
                  offstage: !flags[i].isChecked,
                  child: Image.asset(
                    flagChecked2Icon,
                    width: 13.w,
                    height: 13.w,
                  )),
              right: 10,
              bottom: 0,
            )
          ],
        ),
      ));

      posX += 10;
    }
    callback(totalHeight);
    return widgets;
  }

  @override
  Widget build(BuildContext context) {
    flagWidgets = getEditableFlagsWidget(
        widget.flagModels, ScreenUtil().screenWidth - 150.w, 400, 11, (height) {
      flagHeight = height;
    });

    return Container(
      color: alphaColor,
      child: ConstraintLayout(
        children: [
          Container(
            height: 145.h + 200,
            margin: EdgeInsets.symmetric(horizontal: 45.w),
            decoration: BoxDecoration(
              color: popupViewColor,
              borderRadius: BorderRadius.circular(20.h),
            ),
          ).applyConstraint(
              centerTo: parent,
              left: parent.left.margin(45.w),
              right: parent.right.margin(45.w),
              width: matchConstraint,
              height: 145.h + 200),
          Text(widget.title, style: const TextStyle(fontSize: 17, color: F1TextColor, fontWeight: FontWeight.w700),).applyConstraint(
              top: rId(0).top.margin(29.h),
              left: parent.left,
              right: parent.right),
          LineWidget(width: ScreenUtil().screenWidth - 90.w, height: 0.5.h)
              .applyConstraint(
            left: parent.left.margin(45.w),
            right: parent.right.margin(45.w),
            width: matchConstraint,
            bottom: rId(0).bottom.margin(60.h),
          ),
          LineWidget(width: 0.5.w, height: 60.h).applyConstraint(
            top: rId(2).bottom,
            bottom: rId(0).bottom,
            height: matchConstraint,
            centerHorizontalTo: parent,
          ),
          GestureDetector(
                  onTap: () {
                    widget.entry.remove();
                    OverlayUtils.removeOverlay();
                    widget.callback(-1);
                  },
                  child: F16TitleText(widget.leftBtnText!, color: F2TextColor))
              .applyConstraint(
            top: rId(2).top,
            bottom: rId(3).bottom,
            left: rId(2).left,
            right: rId(3).right,
            clickPadding: EdgeInsets.all(5.w),
          ),
          GestureDetector(
                  onTap: () {
                    widget.entry.remove();
                    OverlayUtils.removeOverlay();
                    if (widget.selectedId == -1) {
                      ToastUtils.showToast(msg: '请选择用户模板');
                      return;
                    }
                    widget.callback(widget.selectedId);
                  },
                  child: F16TitleText(widget.rightBtnText!, color: themeColor))
              .applyConstraint(
            top: rId(2).top,
            bottom: rId(3).bottom,
            right: rId(2).right,
            left: rId(3).left,
            clickPadding: EdgeInsets.all(15.w),
          ),
          SingleChildScrollView(
                  child: Container(
                      height: flagHeight,
                      width: ScreenUtil().screenWidth - 150.w,
                      child: Stack(children: flagWidgets)))
              .applyConstraint(
            left: rId(0).left.margin(15.w),
            right: rId(0).right.margin(15.w),
            top: rId(1).bottom.margin(12.h),
            width: ScreenUtil().screenWidth - 150.w,
            height: 200,
          ),
        ],
      ),
    );
  }

  @override
  void initState() {
    Timer.periodic(const Duration(seconds: 1), (timer) {
      timer.cancel();
      OverlayUtils.insertOverlay(context: context, entry: widget.entry);
    });
  }
}

///选择性别
class SelectSexPicker extends StatefulWidget {
  const SelectSexPicker(
      {Key? key, required this.callback, required this.overlay})
      : super(key: key);

  final Function callback;

  final OverlayEntry overlay;

  ///取消弹框，必传

  @override
  State<SelectSexPicker> createState() => _SelectSexPicker();
}

class _SelectSexPicker extends State<SelectSexPicker> {
  String line = 'line';

  String okBtn = 'okBtn';

  String cancelBtn = 'cancelBtn';

  String picker = 'picker';

  String title = 'title';

  late TextEditingController _controller;

  double btnWidth = (ScreenUtil().screenWidth - 90.w) / 2;

  String sex = 'M';

  @override
  void initState() {
    _controller = TextEditingController();

    Timer.periodic(const Duration(seconds: 1), (timer) {
      timer.cancel();
      OverlayUtils.insertOverlay(context: context, entry: widget.overlay);
    });
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: (){
        widget.overlay!.remove();
        OverlayUtils.removeOverlay();
      },
      child: Container(
        color: alphaColor,
        alignment: Alignment.bottomCenter,
        child: Container(
          height: 280.h,
          decoration: BoxDecoration(
              color: popupViewColor,
              borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(20.h),
                  topRight: Radius.circular(20.h))),
          child: ConstraintLayout(
            children: [
              LineWidget(
                width: 22.w,
                height: 3.h,
                isCorner: true,
              ).applyConstraint(
                  centerHorizontalTo: parent,
                  top: parent.top.margin(6.h),
                  width: 22.w,
                  height: 3.h),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  GestureDetector(
                    onTap: () {
                      widget.overlay.remove();
                      OverlayUtils.removeOverlay();
                    },
                    child: Container(
                      padding: EdgeInsets.all(10.w),
                      child: F15TitleText(
                        '取消',
                        color: F2TextColor,
                      ),
                    ),
                  ),
                  Text(
                    '请选择性别',
                    style: TextStyle(
                        color: F1TextColor,
                        fontSize: 16,
                        fontWeight: FontWeight.w500),
                  ),
                  GestureDetector(
                    onTap: () {
                      widget.overlay.remove();
                      OverlayUtils.removeOverlay();
                      widget.callback(sex);
                    },
                    child: Container(
                      padding: EdgeInsets.all(10.w),
                      child: F15TitleText(
                        '确定',
                        color: themeColor,
                      ),
                    ),
                  ),
                ],
              ).applyConstraint(
                  centerHorizontalTo: parent,
                  top: parent.top.margin(28.h),
                  id: cId(title)),
              CupertinoPicker(
                  itemExtent: 40.h,
                  onSelectedItemChanged: (index) {
                    sex = index == 0 ? 'M' : 'F';
                  },
                  selectionOverlay: Container(
                    height: 40.h,
                    decoration: BoxDecoration(
                        color: const Color(0x305A7BED),
                        borderRadius: BorderRadius.circular(20.h)),
                  ),
                  children: const [
                    Center(
                      child: MyText(
                        '男',
                        color: F1TextColor,
                        fontSize: 20,
                      ),
                    ),
                    Center(
                      child: MyText(
                        '女',
                        color: F1TextColor,
                        fontSize: 20,
                      ),
                    ),
                  ]).applyConstraint(
                  left: parent.left.margin(30.w),
                  right: parent.right.margin(30.w),
                  width: matchConstraint,
                  height: 158.h,
                  top: cId(title).bottom,
                  id: cId(picker)),
              // CommonRadiusBtn(
              //   width: btnWidth,
              //   height: 43.h,
              //   title: '取消',
              //   callback: () {
              //     widget.overlay.remove();
              //     OverlayUtils.removeOverlay();
              //   },
              // ).applyConstraint(
              //     left: cId(picker).left,
              //     top: cId(picker).bottom.margin(27.h),
              //     height: 48.h,
              //     width: btnWidth),
              // CommonBtn(
              //   isEnable: true,
              //   title: '确定',
              //   callback: () {
              //     widget.overlay.remove();
              //     OverlayUtils.removeOverlay();
              //     widget.callback(sex);
              //   },
              // ).applyConstraint(
              //     right: cId(picker).right,
              //     top: cId(picker).bottom.margin(27.h),
              //     height: 48.h,
              //     width: btnWidth),
            ],
          ),
        ),
      ),
    );
  }
}

///单选
class SelectSinglePicker extends StatefulWidget {
  const SelectSinglePicker(
      {Key? key,
      required this.callback,
      required this.overlay,
      required this.items,
      required this.title})
      : super(key: key);

  final Function callback;
  final String title;

  final List<String> items;
  final OverlayEntry overlay;

  ///取消弹框，必传

  @override
  State<SelectSinglePicker> createState() => _SelectSinglePicker();
}

class _SelectSinglePicker extends State<SelectSinglePicker> {
  String line = 'line';

  String okBtn = 'okBtn';

  String cancelBtn = 'cancelBtn';

  String picker = 'picker';

  String title = 'title';

  late TextEditingController _controller;

  double btnWidth = (ScreenUtil().screenWidth - 90.w) / 2;

  String selectedItem = '';

  @override
  void initState() {
    selectedItem = widget.items[0];
    _controller = TextEditingController();

    Timer.periodic(const Duration(seconds: 1), (timer) {
      timer.cancel();
      OverlayUtils.insertOverlay(context: context, entry: widget.overlay);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: alphaColor,
      alignment: Alignment.bottomCenter,
      child: Container(
        height: 280.h,
        decoration: BoxDecoration(
            color: popupViewColor,
            borderRadius: BorderRadius.only(
                topLeft: Radius.circular(20.h),
                topRight: Radius.circular(20.h))),
        child: ConstraintLayout(
          children: [
            LineWidget(
              width: 22.w,
              height: 3.h,
              isCorner: true,
            ).applyConstraint(
                centerHorizontalTo: parent,
                top: parent.top.margin(6.h),
                width: 22.w,
                height: 3.h),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                GestureDetector(
                  onTap: () {
                    widget.overlay.remove();
                    OverlayUtils.removeOverlay();
                  },
                  child: Container(
                    padding: EdgeInsets.all(10.w),
                    child: F15TitleText(
                      '取消',
                      color: F2TextColor,
                    ),
                  ),
                ),
                Text(
                  widget.title,
                  style: TextStyle(
                      color: F1TextColor,
                      fontSize: 16,
                      fontWeight: FontWeight.w500),
                ),
                GestureDetector(
                  onTap: () {
                    widget.overlay.remove();
                    OverlayUtils.removeOverlay();
                    widget.callback(selectedItem);
                  },
                  child: Container(
                    padding: EdgeInsets.all(10.w),
                    child: F15TitleText(
                      '确定',
                      color: themeColor,
                    ),
                  ),
                ),
              ],
            ).applyConstraint(
                centerHorizontalTo: parent,
                top: parent.top.margin(28.h),
                id: cId(title)),
            CupertinoPicker(
                    itemExtent: 40.h,
                    onSelectedItemChanged: (index) {
                      selectedItem = widget.items[index];
                    },
                    selectionOverlay: Container(
                      height: 40.h,
                      decoration: BoxDecoration(
                          color: const Color(0x305A7BED),
                          borderRadius: BorderRadius.circular(20.h)),
                    ),
                    children: _getPickerItem())
                .applyConstraint(
                    left: parent.left.margin(30.w),
                    right: parent.right.margin(30.w),
                    width: matchConstraint,
                    height: 158.h,
                    top: cId(title).bottom,
                    id: cId(picker)),
          ],
        ),
      ),
    );
  }

  List<Widget> _getPickerItem() {
    List<Widget> list = [];
    for (int i = 0; i < widget.items.length; i++) {
      list.add(
        Center(
          child: MyText(
            widget.items[i],
            color: F1TextColor,
            fontSize: 20,
          ),
        ),
      );
    }
    return list;
  }
}

class SelectDatePicker extends StatefulWidget {
  const SelectDatePicker(
      {Key? key,
      required this.callback,
      required this.overlay,
      required this.date,
      required this.title})
      : super(key: key);

  final Function callback;

  final OverlayEntry overlay;

  final String date;

  final String title;

  ///年月日

  ///取消弹框，必传

  @override
  State<SelectDatePicker> createState() => _SelectDatePicker();
}

class _SelectDatePicker extends State<SelectDatePicker> {
  String line = 'line';

  String okBtn = 'okBtn';

  String cancelBtn = 'cancelBtn';

  String year = 'year';
  String month = 'month';
  String day = 'day';

  String title = 'title';

  late TextEditingController _controller;

  List<int> yearList = [];
  List<int> monthList = [];
  List<int> dayList = [];

  int selectYear = 0;
  int selectMonth = 0;
  int selectDay = 0;

  double btnWidth = (ScreenUtil().screenWidth - 90.w) / 2;

  double pickerWidth = (ScreenUtil().screenWidth - 120.w) / 3;

  final FixedExtentScrollController _yearController =
      FixedExtentScrollController();
  final FixedExtentScrollController _monthController =
      FixedExtentScrollController();
  final FixedExtentScrollController _dayController =
      FixedExtentScrollController();

  @override
  void initState() {
    _controller = TextEditingController();

    List<String> times = widget.date.split('-');
    DateTime dateTime =
        DateTime(int.parse(times[0]), int.parse(times[1]), int.parse(times[2]));
    selectYear = dateTime.year;
    selectMonth = dateTime.month;
    selectDay = dateTime.day;

    int curYear = DateTime.now().year;
    for (int i = curYear - 99; i <= curYear; i++) {
      yearList.add(i);
    }

    for (int i = 1; i <= 12; i++) {
      monthList.add(i);
    }

    resetDayList();

    Timer.periodic(const Duration(milliseconds: 50), (timer) {
      _yearController.jumpTo((selectYear - curYear + 99) * 40.h);
      _monthController.jumpTo((selectMonth - 1) * 40.h);
      _dayController.jumpTo((selectDay - 1) * 40.h);

      timer.cancel();
    });

    Timer.periodic(const Duration(seconds: 1), (timer) {
      timer.cancel();
      OverlayUtils.insertOverlay(context: context, entry: widget.overlay);
    });
  }

  void resetDayList() {
    dayList.clear();

    ///当前月份天数
    int days = curMonthDays(selectYear, selectMonth);
    for (int i = 1; i <= days; i++) {
      dayList.add(i);
    }
  }

  int curMonthDays(int year, int month) {
    if (year % 4 == 0 && month == 2) {
      return 29;
    }

    List<int> days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    return days[month - 1];
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: (){
        widget.overlay!.remove();
        OverlayUtils.removeOverlay();
      },
      child: Container(
        color: alphaColor,
        alignment: Alignment.bottomCenter,
        child: Container(
          height: 359.h,
          decoration: BoxDecoration(
              color: popupViewColor,
              borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(20.h),
                  topRight: Radius.circular(20.h))),
          child: ConstraintLayout(
            children: [
              LineWidget(
                width: 22.w,
                height: 3.h,
                isCorner: true,
              ).applyConstraint(
                  centerHorizontalTo: parent,
                  top: parent.top.margin(6.h),
                  width: 22.w,
                  height: 3.h),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  GestureDetector(
                    onTap: () {
                      widget.overlay.remove();
                      OverlayUtils.removeOverlay();
                    },
                    child: Container(
                      padding: EdgeInsets.all(10.w),
                      child: F15TitleText(
                        '取消',
                        color: F2TextColor,
                      ),
                    ),
                  ),
                  Text(
                    widget.title,
                    style: TextStyle(
                        color: F1TextColor,
                        fontSize: 16,
                        fontWeight: FontWeight.w500),
                  ),
                  GestureDetector(
                    onTap: () {
                      widget.overlay.remove();
                      OverlayUtils.removeOverlay();
                      widget.callback(_getSelectDate(), _calculateAge());
                    },
                    child: Container(
                      padding: EdgeInsets.all(10.w),
                      child: F15TitleText(
                        '确定',
                        color: themeColor,
                      ),
                    ),
                  ),
                ],
              ).applyConstraint(
                  centerHorizontalTo: parent,
                  top: parent.top.margin(28.h),
                  id: cId(title)),
              Container(
                height: 40.h,
                decoration: BoxDecoration(
                    color: const Color(0x205A7BED),
                    borderRadius: BorderRadius.circular(20.h)),
              ).applyConstraint(
                  left: parent.left.margin(15.w),
                  right: parent.right.margin(15.w),
                  width: matchConstraint,
                  centerVerticalTo: cId(month),
                  height: 40.h),
              CupertinoPicker(
                      itemExtent: 40.h,
                      squeeze: 1.02.h,
                      scrollController: _yearController,
                      onSelectedItemChanged: (index) {
                        selectYear = yearList[index];
                        setState(() {
                          resetDayList();
                        });
                      },
                      selectionOverlay: Container(),
                      children: _getYearList())
                  .applyConstraint(
                      left: parent.left.margin(30.w),
                      width: pickerWidth,
                      height: 158.h,
                      top: cId(title).bottom.margin(23.h),
                      id: cId(year)),
              CupertinoPicker(
                      itemExtent: 40.h,
                      squeeze: 1.02.h,
                      scrollController: _monthController,
                      onSelectedItemChanged: (index) {
                        selectMonth = monthList[index];
                        setState(() {
                          resetDayList();
                        });
                      },
                      selectionOverlay: Container(),
                      children: _getMonthList())
                  .applyConstraint(
                      width: pickerWidth,
                      centerHorizontalTo: parent,
                      height: 158.h,
                      top: cId(title).bottom.margin(23.h),
                      id: cId(month)),
              CupertinoPicker(
                      itemExtent: 40.h,
                      squeeze: 1.02.h,
                      scrollController: _dayController,
                      onSelectedItemChanged: (index) {
                        selectDay = dayList[index];
                      },
                      selectionOverlay: Container(),
                      children: _getDayList())
                  .applyConstraint(
                      right: parent.right,
                      width: pickerWidth,
                      height: 158.h,
                      top: cId(title).bottom.margin(23.h),
                      id: cId(day)),
              //   CommonRadiusBtn(
              //     width: btnWidth,
              //     height: 43.h,
              //     title: '取消',
              //     callback: () {
              //       widget.overlay.remove();
              //       OverlayUtils.removeOverlay();
              //     },
              //   ).applyConstraint(
              //       left: parent.left.margin(25.w),
              //       top: cId(year).bottom.margin(27.h),
              //       height: 48.h,
              //       width: btnWidth),
              //   CommonBtn(
              //     isEnable: true,
              //     title: '确定',
              //     callback: () {
              //       widget.overlay.remove();
              //       OverlayUtils.removeOverlay();
              //       widget.callback(_getSelectDate(), _calculateAge());
              //     },
              //   ).applyConstraint(
              //       right: parent.right.margin(25.w),
              //       top: cId(day).bottom.margin(27.h),
              //       height: 48.h,
              //       width: btnWidth),
            ],
          ),
        ),
      ),
    );
  }

  String _getSelectDate() {
    String YY = '$selectYear';
    String MM = selectMonth >= 10 ? '$selectMonth' : '0$selectMonth';
    String dd = selectDay >= 10 ? '$selectDay' : '0$selectDay';

    return '$YY-$MM-$dd';
  }

  int _calculateAge() {
    DateTime dateTime = DateTime.now();

    int year = dateTime.year;
    int mon = dateTime.month;
    int day = dateTime.day;

    int age = year - selectYear;

    if (mon < selectMonth || (mon == selectMonth && day < selectDay)) {
      age -= 1;
    }

    return age;
  }

  ///获取所有年份
  List<Widget> _getYearList() {
    List<Widget> years = [];
    for (var element in yearList) {
      String text = '$element年';
      years.add(Center(child: MyText(text, color: F1TextColor, fontSize: 20)));
    }

    return years;
  }

  ///获取月份
  List<Widget> _getMonthList() {
    List<Widget> months = [];
    for (var element in monthList) {
      String text = '$element月';
      months.add(Center(child: MyText(text, color: F1TextColor, fontSize: 20)));
    }

    return months;
  }

  ///获取当天月份天数
  List<Widget> _getDayList() {
    List<Widget> days = [];
    for (var element in dayList) {
      String text = '$element日';
      days.add(Center(child: MyText(text, color: F1TextColor, fontSize: 20)));
    }

    return days;
  }
}

class SelectTimePicker extends StatefulWidget {
  const SelectTimePicker(
      {Key? key,
      required this.callback,
      required this.overlay,
      required this.time})
      : super(key: key);

  final Function callback;

  final OverlayEntry overlay;

  final String time;

  @override
  State<SelectTimePicker> createState() => _SelectTimePicker();
}

class _SelectTimePicker extends State<SelectTimePicker> {
  String line = 'line';
  String okBtn = 'okBtn';
  String cancelBtn = 'cancelBtn';
  String hour = 'hour';
  String minute = 'minute';
  String title = 'title';

  late TextEditingController _controller;

  List<int> hourList = [];
  List<int> minuteList = [];

  int selectHour = 0;
  int selectMinute = 0;

  double btnWidth = (ScreenUtil().screenWidth - 90.w) / 2;

  double pickerWidth = 100.w;
  double pickerSpace = (ScreenUtil().screenWidth - 200.w) / 3;

  final FixedExtentScrollController _hourController =
      FixedExtentScrollController();
  final FixedExtentScrollController _minuteController =
      FixedExtentScrollController();

  @override
  void initState() {
    _controller = TextEditingController();

    List<String> times = widget.time.split(':');
    selectHour = int.parse(times[0]);
    selectMinute = int.parse(times[1]);

    for (int i = 0; i <= 23; i++) {
      hourList.add(i);
    }

    for (int i = 0; i <= 59; i++) {
      minuteList.add(i);
    }
    // resetDayList();

    Timer.periodic(const Duration(milliseconds: 50), (timer) {
      _hourController.jumpTo(selectHour * 40.h);
      _minuteController.jumpTo(selectMinute * 40.h);

      timer.cancel();
    });

    Timer.periodic(const Duration(seconds: 1), (timer) {
      timer.cancel();
      OverlayUtils.insertOverlay(context: context, entry: widget.overlay);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: alphaColor,
      alignment: Alignment.bottomCenter,
      child: Container(
        height: 359.h,
        decoration: BoxDecoration(
            color: popupViewColor,
            borderRadius: BorderRadius.only(
                topLeft: Radius.circular(20.h),
                topRight: Radius.circular(20.h))),
        child: ConstraintLayout(
          children: [
            LineWidget(
              width: 22.w,
              height: 3.h,
              isCorner: true,
            ).applyConstraint(
                centerHorizontalTo: parent,
                top: parent.top.margin(6.h),
                width: 22.w,
                height: 3.h),
            const MyText('请选择时间', color: F1TextColor, fontSize: 17)
                .applyConstraint(
                    centerHorizontalTo: parent,
                    top: parent.top.margin(28.h),
                    id: cId(title)),
            Container(
              height: 40.h,
              decoration: BoxDecoration(
                  color: const Color(0x6F333C41),
                  borderRadius: BorderRadius.circular(20.h)),
            ).applyConstraint(
                left: parent.left.margin(30.w),
                right: parent.right.margin(30.w),
                width: matchConstraint,
                centerVerticalTo: cId(hour),
                height: 40.h),
            CupertinoPicker(
                    itemExtent: 40.h,
                    squeeze: 1.02.h,
                    scrollController: _hourController,
                    onSelectedItemChanged: (index) {
                      selectHour = hourList[index];
                      setState(() {});
                    },
                    selectionOverlay: Container(),
                    children: _getHourList())
                .applyConstraint(
                    left: parent.left.margin(pickerSpace),
                    width: pickerWidth,
                    height: 158.h,
                    top: cId(title).bottom.margin(23.h),
                    id: cId(hour)),
            CupertinoPicker(
                    itemExtent: 40.h,
                    squeeze: 1.02.h,
                    scrollController: _minuteController,
                    onSelectedItemChanged: (index) {
                      selectMinute = minuteList[index];
                      setState(() {
                        // resetDayList();
                      });
                    },
                    selectionOverlay: Container(),
                    children: _getMinuteList())
                .applyConstraint(
                    width: pickerWidth,
                    right: parent.right.margin(pickerSpace),
                    height: 158.h,
                    top: cId(title).bottom.margin(23.h),
                    id: cId(minute)),
            CommonRadiusBtn(
              width: btnWidth,
              height: 43.h,
              title: '取消',
              callback: () {
                widget.overlay.remove();
                OverlayUtils.removeOverlay();
              },
            ).applyConstraint(
                left: parent.left.margin(30.w),
                top: cId(hour).bottom.margin(27.h),
                height: 48.h,
                width: btnWidth),
            CommonBtn(
              isEnable: true,
              title: '确定',
              callback: () {
                widget.overlay.remove();
                OverlayUtils.removeOverlay();
                widget.callback(_getSelectDate());
              },
            ).applyConstraint(
                right: parent.right.margin(30.w),
                top: cId(minute).bottom.margin(27.h),
                height: 48.h,
                width: btnWidth),
          ],
        ),
      ),
    );
  }

  String _getSelectDate() {
    String hh = selectHour >= 10 ? '$selectHour' : '0$selectHour';
    String mm = selectMinute >= 10 ? '$selectMinute' : '0$selectMinute';

    return '$hh:$mm';
  }

  ///获取小时
  List<Widget> _getHourList() {
    List<Widget> hours = [];
    for (var element in hourList) {
      String text = '$element点';
      hours.add(Center(child: MyText(text, color: F1TextColor, fontSize: 20)));
    }

    return hours;
  }

  ///获取分钟
  List<Widget> _getMinuteList() {
    List<Widget> minutes = [];
    for (var element in minuteList) {
      String text = '$element分';
      minutes
          .add(Center(child: MyText(text, color: F1TextColor, fontSize: 20)));
    }

    return minutes;
  }
}

class SelectTimePicker2 extends StatefulWidget {
  const SelectTimePicker2({
    super.key,
    required this.callback,
    required this.overlay,
    required this.title,
    required this.date,
    required this.time,
  });

  final Function callback;

  final OverlayEntry overlay;

  final String title;

  final String date;

  final String time;

  @override
  State<SelectTimePicker2> createState() => _SelectTimePicker2();
}

class _SelectTimePicker2 extends State<SelectTimePicker2> {
  String line = 'line';
  String okBtn = 'okBtn';
  String cancelBtn = 'cancelBtn';
  String hour = 'hour';
  String minute = 'minute';
  String year = 'year';
  String month = 'month';
  String day = 'day';
  String title = 'title';

  late TextEditingController _controller;

  List<int> yearList = [];
  List<int> monthList = [];
  List<int> dayList = [];
  List<int> hourList = [];
  List<int> minuteList = [];

  int selectYear = 0;
  int selectMonth = 0;
  int selectDay = 0;
  int selectHour = 0;
  int selectMinute = 0;

  double btnWidth = (ScreenUtil().screenWidth - 90.w) / 2;

  double pickerWidth = 80.w;
  double pickerSpace = (ScreenUtil().screenWidth - 400.w) / 6;

  final FixedExtentScrollController _yearController =
      FixedExtentScrollController();
  final FixedExtentScrollController _monthController =
      FixedExtentScrollController();
  final FixedExtentScrollController _dayController =
      FixedExtentScrollController();
  final FixedExtentScrollController _hourController =
      FixedExtentScrollController();
  final FixedExtentScrollController _minuteController =
      FixedExtentScrollController();

  void resetDayList() {
    dayList.clear();

    ///当前月份天数
    int days = curMonthDays(selectYear, selectMonth);
    for (int i = 1; i <= days; i++) {
      dayList.add(i);
    }
  }

  int curMonthDays(int year, int month) {
    if (year % 4 == 0 && month == 2) {
      return 29;
    }

    List<int> days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    return days[month - 1];
  }

  ///获取所有年份
  List<Widget> _getYearList() {
    List<Widget> years = [];
    for (var element in yearList) {
      String text = '$element年';
      years.add(Center(child: MyText(text, color: F1TextColor, fontSize: 15)));
    }

    return years;
  }

  ///获取月份
  List<Widget> _getMonthList() {
    List<Widget> months = [];
    for (var element in monthList) {
      String text = '$element月';
      months.add(Center(child: MyText(text, color: F1TextColor, fontSize: 15)));
    }

    return months;
  }

  ///获取当天月份天数
  List<Widget> _getDayList() {
    List<Widget> days = [];
    for (var element in dayList) {
      String text = '$element日';
      days.add(Center(child: MyText(text, color: F1TextColor, fontSize: 15)));
    }

    return days;
  }

  @override
  void initState() {
    _controller = TextEditingController();

    List<String> times = widget.time.split(':');
    selectHour = int.parse(times[0]);
    selectMinute = int.parse(times[1]);

    for (int i = 0; i <= 23; i++) {
      hourList.add(i);
    }

    for (int i = 0; i <= 59; i++) {
      minuteList.add(i);
    }

    List<String> dates = widget.date.split('-');
    DateTime dateTime =
        DateTime(int.parse(dates[0]), int.parse(dates[1]), int.parse(dates[2]));
    selectYear = dateTime.year;
    selectMonth = dateTime.month;
    selectDay = dateTime.day;

    int curYear = DateTime.now().year;
    for (int i = curYear - 99; i <= curYear; i++) {
      yearList.add(i);
    }

    for (int i = 1; i <= 12; i++) {
      monthList.add(i);
    }

    resetDayList();

    Timer.periodic(const Duration(milliseconds: 50), (timer) {
      _hourController.jumpTo(selectHour * 40.h);
      _minuteController.jumpTo(selectMinute * 40.h);
      _yearController.jumpTo((selectYear - curYear + 99) * 40.h);
      _monthController.jumpTo((selectMonth - 1) * 40.h);
      _dayController.jumpTo((selectDay - 1) * 40.h);

      timer.cancel();
    });

    Timer.periodic(const Duration(seconds: 1), (timer) {
      timer.cancel();
      OverlayUtils.insertOverlay(context: context, entry: widget.overlay);
    });

  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: alphaColor,
      alignment: Alignment.bottomCenter,
      child: Container(
        height: 330.h,
        decoration: BoxDecoration(
            color: popupViewColor,
            borderRadius: BorderRadius.only(
                topLeft: Radius.circular(20.h),
                topRight: Radius.circular(20.h))),
        child: ConstraintLayout(
          children: [
            LineWidget(
              width: 22.w,
              height: 3.h,
              isCorner: true,
            ).applyConstraint(
                centerHorizontalTo: parent,
                top: parent.top.margin(6.h),
                width: 22.w,
                height: 3.h),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                GestureDetector(
                  onTap: () {
                    widget.overlay.remove();
                    OverlayUtils.removeOverlay();
                  },
                  child: Container(
                    padding: EdgeInsets.all(10.w),
                    child: F15TitleText(
                      '取消',
                      color: F2TextColor,
                    ),
                  ),
                ),
                Text(
                  widget.title,
                  style: TextStyle(
                      color: F1TextColor,
                      fontSize: 16,
                      fontWeight: FontWeight.w500),
                ),
                GestureDetector(
                  onTap: () {
                    widget.overlay.remove();
                    OverlayUtils.removeOverlay();
                    widget.callback(_getSelectDate());
                  },
                  child: Container(
                    padding: EdgeInsets.all(10.w),
                    child: F15TitleText(
                      '确定',
                      color: themeColor,
                    ),
                  ),
                ),
              ],
            ).applyConstraint(
                centerHorizontalTo: parent,
                top: parent.top.margin(28.h),
                id: cId(title)),
            Container(
              height: 40.h,
              decoration: BoxDecoration(
                  color: const Color(0x305A7BED),
                  borderRadius: BorderRadius.circular(20.h)),
            ).applyConstraint(
                left: parent.left.margin(5.w),
                right: parent.right.margin(5.w),
                width: matchConstraint,
                centerVerticalTo: cId(hour),
                height: 40.h),
            CupertinoPicker(
                    itemExtent: 40.h,
                    squeeze: 1.02.h,
                    scrollController: _yearController,
                    onSelectedItemChanged: (index) {
                      selectYear = yearList[index];
                      _checkTime();
                      setState(() {
                        resetDayList();
                      });
                    },
                    selectionOverlay: Container(),
                    children: _getYearList())
                .applyConstraint(
                    left: parent.left.margin(pickerSpace),
                    width: pickerWidth,
                    height: 158.h,
                    top: cId(title).bottom.margin(30.h),
                    id: cId(year)),
            CupertinoPicker(
                    itemExtent: 40.h,
                    squeeze: 1.02.h,
                    scrollController: _monthController,
                    onSelectedItemChanged: (index) {
                      selectMonth = monthList[index];
                      _checkTime();
                      setState(() {
                        resetDayList();
                      });
                    },
                    selectionOverlay: Container(),
                    children: _getMonthList())
                .applyConstraint(
                    width: pickerWidth,
                    left: cId(year).right.margin(pickerSpace),
                    height: 158.h,
                    top: cId(title).bottom.margin(30.h),
                    id: cId(month)),
            CupertinoPicker(
                    itemExtent: 40.h,
                    squeeze: 1.02.h,
                    scrollController: _dayController,
                    onSelectedItemChanged: (index) {
                      selectDay = dayList[index];
                      _checkTime();
                      setState(() {

                      });
                    },
                    selectionOverlay: Container(),
                    children: _getDayList())
                .applyConstraint(
                    left: cId(month).right.margin(pickerSpace),
                    width: pickerWidth,
                    height: 158.h,
                    top: cId(title).bottom.margin(30.h),
                    id: cId(day)),
            CupertinoPicker(
                    itemExtent: 40.h,
                    squeeze: 1.02.h,
                    scrollController: _hourController,
                    onSelectedItemChanged: (index) {
                      selectHour = hourList[index];
                      _checkTime();
                      setState(() {});
                    },
                    selectionOverlay: Container(),
                    children: _getHourList())
                .applyConstraint(
                    left: cId(day).right.margin(pickerSpace),
                    width: pickerWidth,
                    height: 158.h,
                    top: cId(title).bottom.margin(30.h),
                    id: cId(hour)),
            CupertinoPicker(
                    itemExtent: 40.h,
                    squeeze: 1.02.h,
                    scrollController: _minuteController,
                    onSelectedItemChanged: (index) {
                      selectMinute = minuteList[index];
                      _checkTime();
                      setState(() {
                        // resetDayList();
                      });
                    },
                    selectionOverlay: Container(),
                    children: _getMinuteList())
                .applyConstraint(
                    width: pickerWidth,
                    right: parent.right,
                    height: 158.h,
                    top: cId(title).bottom.margin(30.h),
                    id: cId(minute)),
            F12TitleText('回收时间：${_getSelectDate()}', color: Color(0xFF262626)).applyConstraint(
              left: parent.left,
              right: parent.right,
              bottom: parent.bottom.margin(30.h),
            ),
            // CommonRadiusBtn(
            //   width: btnWidth,
            //   height: 43.h,
            //   title: '取消',
            //   callback: () {
            //     widget.overlay.remove();
            //     OverlayUtils.removeOverlay();
            //   },
            // ).applyConstraint(
            //     left: parent.left.margin(30.w),
            //     top: cId(title).bottom.margin(27.h),
            //     height: 48.h,
            //     width: btnWidth),
            // CommonBtn(
            //   isEnable: true,
            //   title: '确定',
            //   callback: () {
            //     widget.overlay.remove();
            //     OverlayUtils.removeOverlay();
            //     widget.callback(_getSelectDate());
            //   },
            // ).applyConstraint(
            //     right: parent.right.margin(30.w),
            //     top: cId(title).bottom.margin(27.h),
            //     height: 48.h,
            //     width: btnWidth),
          ],
        ),
      ),
    );
  }

  String _getSelectDate() {
    String YY = '$selectYear';
    String MM = selectMonth >= 10 ? '$selectMonth' : '0$selectMonth';
    String dd = selectDay >= 10 ? '$selectDay' : '0$selectDay';

    String hh = selectHour >= 10 ? '$selectHour' : '0$selectHour';
    String mm = selectMinute >= 10 ? '$selectMinute' : '0$selectMinute';

    return '$YY-$MM-$dd $hh:$mm';
  }
  ///id = 0,1,2,3,4 年月日时分
  void _checkTime() {

    DateTime dateTime = DateTime.now();
    int year = dateTime.year;
    int month = dateTime.month;
    int day = dateTime.day;
    int hour = dateTime.hour;
    int minute = dateTime.minute;

    if (selectYear > year) {
      selectYear = year;
      _yearController.jumpTo((selectYear - year + 99) * 40.h);
    } else if (selectYear == year) {
      if (selectMonth > month) {
        selectMonth = month;
        _monthController.jumpTo((selectMonth - 1) * 40.h);
      } else if (selectMonth == month) {
        if (selectDay > day) {
          selectDay = day;
          _dayController.jumpTo((selectDay - 1) * 40.h);
        } else if (selectDay == day) {
          if (selectHour > hour) {
            LogUtils.log('1234');
            selectHour = hour;
            _hourController.jumpTo(selectHour * 40.h);
          } else if (selectHour == hour) {
            if (selectMinute > minute) {
              selectMinute = minute;
              _minuteController.jumpTo(selectMinute * 40.h);
            }
          }
        }
      }
    }
    LogUtils.log('hour=$hour');
    LogUtils.log('selectHour=$selectHour');
  }

  ///获取小时
  List<Widget> _getHourList() {
    List<Widget> hours = [];
    for (var element in hourList) {
      String text = '$element点';
      hours.add(Center(child: MyText(text, color: F1TextColor, fontSize: 15)));
    }

    return hours;
  }

  ///获取分钟
  List<Widget> _getMinuteList() {
    List<Widget> minutes = [];
    for (var element in minuteList) {
      String text = '$element分';
      minutes
          .add(Center(child: MyText(text, color: F1TextColor, fontSize: 15)));
    }

    return minutes;
  }
}

class AwakeningAlertView extends StatefulWidget {
  const AwakeningAlertView(
      {super.key, required this.topX, required this.topY, required this.entry});

  final OverlayEntry entry;
  final double topX;
  final double topY;

  @override
  State<AwakeningAlertView> createState() => _AwakeningAlertViewState();
}

class _AwakeningAlertViewState extends State<AwakeningAlertView> {
  @override
  Widget build(BuildContext context) {
    return Container(
      color: alphaColor,
      child: ConstraintLayout(
        children: [
          CustomPaint(
            painter: TopTrianglePainter(),
            size: Size(30, 15),
          ).applyConstraint(
            left: parent.left.margin(widget.topX),
            top: parent.top.margin(widget.topY),
            width: 30,
            height: 15,
          ),
          Container(
            width: 300,
            height: 160,
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.all(Radius.circular(10)),
            ),
          ).applyConstraint(
            left: rId(0).left.margin(-155),
            width: 300,
            top: rId(0).bottom.margin(-1),
            height: 160,
          ),
          Text(
            '使用说明',
            style: TextStyle(
                fontSize: 16, fontWeight: FontWeight.w600, color: F1TextColor),
          ).applyConstraint(
            left: rId(1).left.margin(15),
            top: rId(1).top.margin(10),
          ),
          GestureDetector(
                  onTap: () {
                    widget.entry!.remove();
                  },
                  child: Image.asset(
                    aboutCloseIcon,
                    width: 10,
                    height: 10,
                  ))
              .applyConstraint(
                  top: rId(1).top.margin(20),
                  right: rId(1).right.margin(20),
                  clickPadding: EdgeInsets.all(40),
                  size: 10),
          LineWidget(
            width: 1,
            height: 1,
            color: lineColor,
          ).applyConstraint(
              left: rId(1).left,
              right: rId(1).right,
              width: matchConstraint,
              top: rId(2).bottom.margin(5),
              height: 0.5),
          Text.rich(TextSpan(children: [
            TextSpan(
                text: '事件标定：',
                style: TextStyle(
                    fontSize: 13,
                    fontWeight: FontWeight.w600,
                    color: F1TextColor)),
            TextSpan(
                text: '长按“微觉醒”按钮，拖动至下方脑电图表区域，松开即完成标定。',
                style: TextStyle(fontSize: 13, color: F1TextColor)),
          ])).applyConstraint(
              left: rId(2).left,
              right: rId(3).right,
              width: matchConstraint,
              top: rId(4).bottom.margin(10)),
          Text.rich(TextSpan(children: [
            TextSpan(
                text: '事件移除：',
                style: TextStyle(
                    fontSize: 13,
                    fontWeight: FontWeight.w600,
                    color: F1TextColor)),
            TextSpan(
                text: '长按“微觉醒”事件，拖动移出下方脑电图表区域，松开即完成移除。',
                style: TextStyle(fontSize: 13, color: F1TextColor)),
          ])).applyConstraint(
              left: rId(2).left,
              right: rId(3).right,
              width: matchConstraint,
              top: rId(5).bottom.margin(10)),
        ],
      ),
    );
  }
}
class FilterAlertView extends StatefulWidget {
  const FilterAlertView(
      {super.key, required this.topX, required this.topY, required this.entry, required this.callback});

  final OverlayEntry entry;
  final double topX;
  final double topY;
  final Function callback;

  @override
  State<FilterAlertView> createState() => _FilterAlertViewState();
}

class _FilterAlertViewState extends State<FilterAlertView> {
  List<String> type = [
    '高通',
    '低通',
    '带通',
    '带阻',
  ];

  @override
  Widget build(BuildContext context) {
    return Container(
      color: alphaColor,
      child: ConstraintLayout(
        children: [
          GestureDetector(
            onTap: (){
              widget.entry!.remove();
            },
          ).applyConstraint(
            topLeftTo: parent,
            bottomRightTo: parent,
            width: matchConstraint,
            height: matchConstraint
          ),
          CustomPaint(
            painter: RightTrianglePainter(),
            size: Size(15, 30),
          ).applyConstraint(
            right: parent.left.margin(-widget.topX),
            top: parent.top.margin(widget.topY),
            width: 15,
            height: 30,
          ),
          Container(
            width: 100,
            height: 160,
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.all(Radius.circular(10)),
            ),
            child: Column(
              children: [
                _getItem(0, 100, 40, true),
                _getItem(1, 100, 40, true),
                _getItem(2, 100, 40, true),
                _getItem(3, 100, 40, false),
              ],
            ),
          ).applyConstraint(
            right: rId(1).left,
            width: 100,
            centerVerticalTo: parent,
            height: 160,
          )
        ],
      ),
    );
  }
  Widget _getItem(int id, double width, double height, bool hasLine) {
    return GestureDetector(
      onTap: (){
        widget.entry.remove();
        widget.callback(id);
      },
      child: Container(
        width: width,
        height: height,
        child: Column(
          children: [
            Expanded(child: Center(child: F13TitleText(type[id], color: Colors.black))),
            Visibility(visible: hasLine, child: LineWidget(color: lineColor, width: width, height: 0.5,))
          ],
        ),
      ),
    );
  }
}
///方向向上的三角形
class TopTrianglePainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    var paint = Paint()..color = Colors.white;
    var path = Path();
    path.moveTo(size.width / 2, 0);
    path.lineTo(0, size.height);
    path.lineTo(size.width, size.height);
    path.close();
    canvas.drawPath(path, paint);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) => false;
}
///方向向右的三角形
class RightTrianglePainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    var paint = Paint()..color = Colors.white;
    var path = Path();
    path.moveTo(0, 0);
    path.lineTo(0, size.height);
    path.lineTo(size.width, size.height/2);
    path.close();
    canvas.drawPath(path, paint);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) => false;
}
